{"componentChunkName":"component---src-templates-post-jsx","path":"/[CS]Trie/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"44f6bf8c-3235-5ff7-9d5f-f7c816218acb","excerpt":"🧷 트라이 효율적인 문자열 저장 및 탐색이 가능한 자료구조이다. 원래는  로 불렸었다. 하지만 말로 할 때  와 구분되지 않는 경향이 있어  로 불리기 시작했다. 수 많은 문자열을 저장하였는데 입력으로 어떤 문자열이 주어졌을 때, 내가 저장한 문자열에 포함된 문자열인지 알 수 있는 방법은 아래와 같은 방식들이 있을 것이다. 단순 비교 단순하게 전체 문자열…","html":"<h2>🧷 트라이</h2>\n<p>효율적인 문자열 저장 및 탐색이 가능한 자료구조이다.</p>\n<blockquote>\n<p>원래는 <code class=\"language-text\">Tri</code> 로 불렸었다. 하지만 말로 할 때 <code class=\"language-text\">Tree</code> 와 구분되지 않는 경향이 있어 <code class=\"language-text\">Trie(트라이)</code> 로 불리기 시작했다.</p>\n</blockquote>\n<p>수 많은 문자열을 저장하였는데 입력으로 어떤 문자열이 주어졌을 때, 내가 저장한 문자열에 포함된 문자열인지 알 수 있는 방법은 아래와 같은 방식들이 있을 것이다.</p>\n<ol>\n<li>\n<p><strong>단순 비교</strong></p>\n<ul>\n<li>단순하게 전체 문자열의 처음부터 끝까지 개별 문자를 비교하는 방식</li>\n<li>최대 문자열 길이 <code class=\"language-text\">m</code>, 전체 문자 개수 <code class=\"language-text\">n</code> 개일 경우, 시간복잡도: <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>n</mi><mi>m</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(nm)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\">n</span><span class=\"mord mathnormal\">m</span><span class=\"mclose\">)</span></span></span></span></li>\n</ul>\n</li>\n<li>\n<p><strong>이진 탐색 기법</strong></p>\n<ul>\n<li>전체 문자열을 사전 순으로 배열 저장 후, 중간 값과 비교해 사전적으로 이전이면 좌측의 반 / 이후면 우측의 반으로 비교 반복 방식</li>\n<li>최대 문자열 길이 <code class=\"language-text\">m</code>, 전체 문자 개수 <code class=\"language-text\">n</code> 개일 경우, 시간복잡도: 정렬: <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>n</mi><mi>m</mi><mi>l</mi><mi>o</mi><mi>g</mi><mi>n</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(nmlogn)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\">n</span><span class=\"mord mathnormal\">m</span><span class=\"mord mathnormal\" style=\"margin-right:0.01968em;\">l</span><span class=\"mord mathnormal\">o</span><span class=\"mord mathnormal\" style=\"margin-right:0.03588em;\">g</span><span class=\"mord mathnormal\">n</span><span class=\"mclose\">)</span></span></span></span> / 탐색: <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>m</mi><mi>l</mi><mi>o</mi><mi>g</mi><mi>n</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(mlogn)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\">m</span><span class=\"mord mathnormal\" style=\"margin-right:0.01968em;\">l</span><span class=\"mord mathnormal\">o</span><span class=\"mord mathnormal\" style=\"margin-right:0.03588em;\">g</span><span class=\"mord mathnormal\">n</span><span class=\"mclose\">)</span></span></span></span> 즉, <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>n</mi><mi>m</mi><mi>l</mi><mi>o</mi><mi>g</mi><mi>n</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(nmlogn)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\">n</span><span class=\"mord mathnormal\">m</span><span class=\"mord mathnormal\" style=\"margin-right:0.01968em;\">l</span><span class=\"mord mathnormal\">o</span><span class=\"mord mathnormal\" style=\"margin-right:0.03588em;\">g</span><span class=\"mord mathnormal\">n</span><span class=\"mclose\">)</span></span></span></span></li>\n</ul>\n</li>\n<li>\n<p><strong>트라이(<code class=\"language-text\">Trie</code>)</strong></p>\n<ul>\n<li>K-진 트리 구조를 통해 문자열을 저장하는 방식</li>\n<li><code class=\"language-text\">game</code> 이라는 단어를 찾는다면, <code class=\"language-text\">g</code> 를 찾고 순서대로 <code class=\"language-text\">a</code>, <code class=\"language-text\">m</code>, <code class=\"language-text\">e</code> 를 찾는데, 이를 트리형식으로 구현한 것</li>\n<li>맨 앞의 접두어(prefix)부터 시작하여 단어 전체를 찾아가는 과정이므로 접두사 트리(Prefix-Tree)라고도 한다.</li>\n<li>문자열 저장을 위한 공간을 많이 쓰지만 탐색에 매우 효율적이라는 특성을 갖는다.</li>\n<li>\n<p>최대 문자열 길이 <code class=\"language-text\">m</code> 일 때 문자의 개수와 무관하게 시간복잡도: <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>m</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(m)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\">m</span><span class=\"mclose\">)</span></span></span></span></p>\n<ul>\n<li>문자열 길이가 너무 커서 <code class=\"language-text\">Map</code> 등을 이용해 동적 할당을 해야 하는 경우 <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>m</mi><mi>l</mi><mi>o</mi><mi>g</mi><mi>n</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(mlogn)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\">m</span><span class=\"mord mathnormal\" style=\"margin-right:0.01968em;\">l</span><span class=\"mord mathnormal\">o</span><span class=\"mord mathnormal\" style=\"margin-right:0.03588em;\">g</span><span class=\"mord mathnormal\">n</span><span class=\"mclose\">)</span></span></span></span>만큼 소요할 수 있다.</li>\n</ul>\n</li>\n</ul>\n</li>\n</ol>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">{&quot;bar&quot;, &quot;bag&quot;, &quot;bark&quot;, &quot;dog&quot;, &quot;do&quot;, &quot;door&quot;}</code>\n        </deckgo-highlight-code>\n<img src='https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FHUT56%2FbtqLElE8hac%2FJkLnmHIMelPA74KhdBS5D1%2Fimg.png' width='50%'>\n<h3>🪚 장단점</h3>\n<p>트라이는 해시 테이블을 대체하는 데 사용될 수 있다.</p>\n<p><strong>장점</strong></p>\n<ul>\n<li>\n<p>불완전한 해시 함수를 사용하는 해시테이블과 비교할 때, 자료에 접근할 때 최악의 경우 더 유리한 시간복잡도를 갖는다. </p>\n<ul>\n<li>m이 탐색할 문자열의 길이일 때 시간복잡도는 <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>m</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(m)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\">m</span><span class=\"mclose\">)</span></span></span></span>이다. </li>\n<li>보통 해시테이블은 탐색 시간이 <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mn>1</mn><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(1)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord\">1</span><span class=\"mclose\">)</span></span></span></span>이고 해시 함수 평가 시간이 <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>m</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(m)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\">m</span><span class=\"mclose\">)</span></span></span></span>이지만, 불완전한 해시 테이블은 키 충돌이 일어날 수 있으므로, <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>N</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(N)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\" style=\"margin-right:0.10903em;\">N</span><span class=\"mclose\">)</span></span></span></span>이 될 수 있다.</li>\n</ul>\n</li>\n<li>트라이에서는 키 충돌이 일어나지 않는다.</li>\n<li>여러 값이 하나의 키와 연관되어 있지 않는 한 버킷이 필요 없다.</li>\n<li>해시 함수가 없어도 된다. 키가 늘어날 때 해시 함수를 변경할 필요도 없다.</li>\n<li>모든 항목이 키에 따라 사전순으로 정렬되어 있다.</li>\n</ul>\n<p><strong>단점</strong></p>\n<ul>\n<li>\n<p>조회는 해시 테이블보다 느릴 수 있다. </p>\n<ul>\n<li>특히 주 메모리에 비해 임의 접근 비용이 큰 하드 디스크 드라이브와 같은 보조 기억장치에서 직접 읽는다면 더욱 그렇다.</li>\n</ul>\n</li>\n<li>부동소수점과 같이 문자열로 장황하게 표시되는 자료의 경우 무의미하게 길게 늘어진 접두사와 노드를 가질 수 있다. </li>\n<li>\n<p>트라이가 메모리를 더 소비할 수 있다. </p>\n<ul>\n<li>대부분의 해시 테이블에서는 전체 항목을 하나의 메모리 청크에 올리곤 하지만, 트라이에서는 검색 문자열의 각 문자마다 메모리가 할당될 수 있다.</li>\n</ul>\n</li>\n</ul>\n<h3>🪚 구현</h3>\n<blockquote>\n<p>트리 구조의 각 노드에는 <strong>각 문자열의 일부를 포함</strong>하며, <strong>자신과 연결되는 문자열의 일부</strong>를 가지고 있어야 한다는 점을 명심!</p>\n</blockquote>\n<p><strong>생성자/클래스 정의</strong></p>\n<ul>\n<li>루트 노드는 아무런 문자열도 포함하지 않고 모든 문자열의 접두사들을 자식 배열로 갖고 있어야 한다.</li>\n<li><code class=\"language-text\">Node</code> 클래스는 각 <code class=\"language-text\">Node</code> 의 정보를 정의한 클래스로, 자신의 문자, 연결되는 문자들의 정보를 갖고 있고 문자열이 완성되는가 여부 또한 저장하고 있다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">class Trie {\n  Node root;\n  static final int ALPHABET_SIZE = 26; // 알파벳 개수: 26\n\n  public Trie() {\n    this.root = new Node();\n    this.root.val = &#39; &#39;;\n  }\n\n  public static class Node {\n    Node[] child = new Node[ALPHABET_SIZE]; // 뒤로 연결되는 문자열을 index화하여 저장하는 배열\n    boolean isTerminal = false; // 현재 노드가 문자열의 마지막인지 여부\n    int childNum = 0; // 현재 노드에 연결된 문자열 개수\n    char val; // 현재 노드의 값\n  }\n}</code>\n        </deckgo-highlight-code>\n<p><strong>문자열 삽입(insert, charToInt)</strong></p>\n<ul>\n<li><code class=\"language-text\">charToInt()</code> 메소드는 각 문자열의 1개 단어를 <code class=\"language-text\">int</code> 형 숫자로 변환해주는 메소드다.</li>\n<li><code class=\"language-text\">insert()</code> 메소드는 전체 문자열을 쪼개서 각 노드(<code class=\"language-text\">Node</code>)에 저장하는 메소드다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">private int charToInt(char c) {\n  return c - &#39;a&#39;; // 소문자만 취급한다는 가정하에 `a`를 뺀다.\n}\n\npublic void insert(String str) {\n  int len = str.length();\n  Node cur = this.root; \n\n  for (int i = 0; i &lt; len; i++) {\n    char c = str.charAt(i);\n    int num = this.charToInt(c);\n\n    if (cur.child[num] == null) { // 기존에 null이면 연결 문자열로 처음 추가되는 것\n      cur.child[num] = new Node();\n      cur.child[num].val = c;\n      cur.childNum++;\n    }\n\n    cur = cur.child[num];\n  }\n  cur.isTerminal = true;\n}</code>\n        </deckgo-highlight-code>\n<p><strong>찾기(find)</strong></p>\n<ul>\n<li>단어를 저장했으면 저장되어 있는지 확인할 수 있어야 한다. </li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public boolean find(String str) {\n  int len = str.length();\n  Node cur = this.root;\n\n  for (int i = 0; i &lt; len; i++) {\n    char c = str.charAt(i);\n    int num = this.charToInt(c);\n\n    if (cur.child[num] == null) return false;\n    cur = cur.child[num];\n  }\n\n  return cur != null &amp;&amp; cur.isTerminal;\n}</code>\n        </deckgo-highlight-code>\n<p><strong>전체 저장된 문자열 내역 출력</strong></p>\n<ul>\n<li>모든 저장된 단어의 내역을 알기 쉽게 출력할 수 있도록 하는 메소드를 구현해볼 수 있다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">private char intToChar(int i) {\n  return (char) (i + (int) &#39;a&#39;);\n}\n\n// 사용자가 간편히 호출만 하면 되는 함수\npublic void printTrie() {\n  this.printTrie(this.root, 0, new StringBuilder());\n}\n\n// 내부에서 재귀적으로 순환하여 노드에 저장된 값들 추출해 출력\nprivate void printTrie(Node node, int idx, StringBuilder sb) {\n  Node cur = node;\n  Node[] child = cur.child;\n  StringBuilder builder = new StringBuilder(sb);\n\n  // 루트 노드에는 저장된 것이 없으므로 그 외의 경우에만 append\n  if (!cur.equals(this.root)) builder.append(intToChar(idx));\n\n  // 완성 노드라면 출력\n  if (cur.isTerminal) System.out.println(builder);\n\n  // 연결된 노드들을 순환하기 위해 반복문 사용\n  for (int i = 0; i &lt; ALPHABET_SIZE; i++) {\n    // null이라면 저장된 것이 없으므로 패스\n    if (cur.child[i] == null) continue;\n\n    printTrie(child[i], i, builder);\n  }\n}</code>\n        </deckgo-highlight-code>\n<p><strong>삭제</strong></p>\n<ul>\n<li>삭제는 재귀적으로 <strong>bottom-up</strong> 방식으로 진행되고, 3가지 경우가 있다.</li>\n<li>\n<p>삭제할 문자가 다른 문자의 접두사인 경우 - <code class=\"language-text\">isTerminal</code> 을 <code class=\"language-text\">false</code> 변경</p>\n<ol>\n<li><code class=\"language-text\">Do</code> 는 <code class=\"language-text\">Door</code> 의 접두사가 된다. 따라서, <code class=\"language-text\">Do</code> 를 삭제한다면 <code class=\"language-text\">D</code> , <code class=\"language-text\">o</code> 에서 <code class=\"language-text\">o</code> 에 <code class=\"language-text\">isTerminal</code> 만 <code class=\"language-text\">false</code> 로 변경한다.</li>\n<li>단순히 삭제하면 <code class=\"language-text\">Door</code> 또한 사라지게 된다.</li>\n</ol>\n</li>\n<li>삭제할 문자가 고유하여 다른 문자와 연관이 없는 경우 - 관련 모든 노드 삭제</li>\n<li>\n<p>삭제할 문자의 일부가 전체 삭제 문자의 접두사인 경우 - 다른 문자에 영항가지 않는 곳까지만 삭제</p>\n<ol>\n<li><code class=\"language-text\">Door</code> 를 삭제하려고 한다면 <code class=\"language-text\">Do</code> 가 있기에, 전체 삭제를 할 수 없고 <code class=\"language-text\">Door</code> 에서 뒤의 <code class=\"language-text\">o</code> , <code class=\"language-text\">r</code> 만 삭제한다.</li>\n</ol>\n</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public void delete(String str) {\n  delete(this.root, str, 0);\n}\n\nprivate void delete(Node cur, String str, int idx) {\n  int len = str.length();\n\n  if ((cur.childNum == 0 &amp;&amp; idx != len) || (idx == len &amp;&amp; !cur.isTerminal)) {\n    throw new NoSuchElementException(&quot;Value&quot; + str + &quot; does not exist in Trie!&quot;);\n  }\n\n  if (idx == len) {\n    cur.isTerminal = false;\n\n    if (cur.childNum == 0) cur = null;\n    else {\n      char c = str.charAt(idx);\n      int num = charToInt(c);\n\n      delete(cur.child[num], str, idx + 1);\n\n      if (cur.child[num] == null) cur.childNum--;\n\n      if (cur.childNum == 0 &amp;&amp; !cur.isTerminal) cur = null;\n    }\n  }\n}</code>\n        </deckgo-highlight-code>\n<blockquote>\n<p>실제로는 <code class=\"language-text\">HashMap</code> 을 사용해 구현하는 것이 더 효율적이다. 아래는 이를 사용한 구현이다.</p>\n</blockquote>\n<p><strong>클래스 생성</strong></p>\n<ul>\n<li><code class=\"language-text\">TrieNode</code> 는 자식노드 맵과 <code class=\"language-text\">isLastChar</code> 를 가지고 있다.</li>\n<li><code class=\"language-text\">isLastChar</code> 는 'DEV'라는 단어에서 [D], [E]는 마지막 글자가 아니지만 [V]는 마지막 글자로, 한 단어가 완성되는 시점임을 알 수 있도록 하는 값이다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class TrieNode {\n\tprivate Map&lt;Character, TrieNode&gt; childNodes = new HashMap&lt;&gt;();\n\t// 마지막 글자 여부\n\tprivate boolean isLastChar;\n\n\t// 자식 노드 맵 Getter\n\tMap&lt;Character, TrieNode&gt; getChildNodes() {\n\t\treturn this.childNodes;\n\t}\n\n\t// 마지막 글자인지 여부 Getter\n\tboolean isLastChar() {\n\t\treturn this.isLastChar;\n\t}\n\n\t// 마지막 글자인지 여부 Setter\n\tvoid setIsLastChar(boolean isLastChar) {\n\t\tthis.isLastChar = isLastChar;\n\t}\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>Trie는 기본적으로 <strong>빈 문자열을 가지는 루트 노드</strong>만 가지고 있다.</li>\n<li>이 후에 나올 <code class=\"language-text\">insert()</code> 를 통해 단어를 넣어 그에 맞게 자식 노드가 생성된다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class Trie {\n\tprivate TrieNode rootNode;\n\n\tpublic Trie() {\n\t\trootNode = new TrieNode();\n\t}\n}</code>\n        </deckgo-highlight-code>\n<p><strong>insert</strong></p>\n<ul>\n<li>\n<p>입력받은 단어의 각 알파벳을 계층구조의 자식 노드로 만들어 넣는다.</p>\n<ul>\n<li>이미 같은 알파벳이 존재하면 공통 접두어까지는 생성하지 않는다.</li>\n</ul>\n</li>\n<li>즉, 해당 계층 문자의 자식 노드가 존재하지 않을 때만 자식 노드를 생성해준다.</li>\n<li>이후 마지막 글자에는 \"여기까지를 끝으로 하는 단어가 존재한다\"는 표시를 위해 <code class=\"language-text\">isLastChar</code> 를 <code class=\"language-text\">true</code> 로 해준다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">void insert(String word) {\n\tTrieNode thisNode = this.rootNode;\n\n\tfor (int i = 0; i &lt; word.length(); i++) {\n\t\tthisNode = thisNode.getChildNodes().computeIfAbsent(word.charAt(i), c -&gt; new TrieNode());\n\t}\n\tthisNode.setIsLastChar(true);\n}</code>\n        </deckgo-highlight-code>\n<p><strong>contains</strong></p>\n<ul>\n<li>\n<p>특정 단어가 Trie에 존재하는지를 확인하기 위해서는 아래 2가지 조건을 만족해야 한다.</p>\n<ul>\n<li>루트 노드부터 순서대로 알파벳이 일치하는 자식 노드들이 존재할 것</li>\n<li>해당 단어의 마지막 글자에 해당하는 노드의 <code class=\"language-text\">isLastChar</code> 가 <code class=\"language-text\">true</code> 일 것</li>\n</ul>\n</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">boolean contains(String word) {\n\tTrieNode thisNode = this.rootNode;\n\n\tfor (int i = 0; i &lt; word.length(); i++) {\n\t\tchar character = word.charAt(i);\n\t\tTrieNode node = thisNode.getChildNodes().get(character);\n\n\t\tif (node == null) return false;\n\n\t\tthisNode = node;\n\t}\n\n\treturn thisNode.isLastChar();\n}</code>\n        </deckgo-highlight-code>\n<p><strong>delete</strong></p>\n<ul>\n<li>Trie에 넣었던 단어를 삭제하는 과정이다.</li>\n<li><code class=\"language-text\">contains()</code> 처럼 주어진 단어를 찾아 하위 노드로 단어 길이만큼 내려간다.</li>\n<li>단, 노드들이 부모 노드의 정보를 가지고 있지 않기에, 하위 노드로 내려가며 삭제 대상 단어를 탐색하고 다시 올라오면서 삭제하는 과정이 <strong>콜백</strong>형식으로 구현되어야 한다는 것이다.</li>\n</ul>\n<p>그리고 아래의 삭제 조건들을 확인해야 한다.</p>\n<ol>\n<li>자식 노드를 가지고 있지 않아야 한다.</li>\n<li>삭제를 시작하는 첫 노드는 <code class=\"language-text\">isLastChar == true</code> 여야 한다.</li>\n<li>삭제를 진행하는 중에는 <code class=\"language-text\">isLastChar == false</code> 여야 한다.</li>\n</ol>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">void delete(String word) {\n\tdelete(this.rootNode, word, 0);\n}\n\t\nprivate void delete(TrieNode thisNode, String word, int index) {\n    char character = word.charAt(index);\n    \n    // Trie에 없는 단어인 경우 에러 출력\n    if(!thisNode.getChildNodes().containsKey(character))\n        throw new Error(&quot;There is no [&quot; + word + &quot;] in this Trie.&quot;);\n              \n    TrieNode childNode = thisNode.getChildNodes().get(character);\n    index++;\n      \n    // 단어의 길이만큼 하위 노드로 재귀\n    if(index == word.length()) {\n      // 삭제조건 2번 항목\n      // PO와 같이 노드는 존재하지만 insert한 단어가 아닌 경우 에러 출력\n      if (!childNode.isLastChar()) \n          throw new Error(&quot;There is no [&quot; + word + &quot;] in this Trie.&quot;);\n        \n      childNode.setIsLastChar(false);\n      // 삭제조건 1번 항목\n      // 삭제 대상 단어의 제일 끝으로써 자식 노드가 없으면(이 단어를 포함하는 더 긴 단어가 없으면) 삭제 시작\n      if (childNode.getChildNodes().isEmpty())\n          thisNode.getChildNodes().remove(character);\n    } else {\n      delete(childNode, word, index); // 콜백함수부분\n      // 삭제조건 1,3번 항목\n      // 삭제 중, 자식 노드가 없고 현재 노드로 끝나는 다른 단어가 없는 경우 이 노드 삭제\n      if(!childNode.isLastChar() &amp;&amp; childNode.getChildNodes().isEmpty())\n          thisNode.getChildNodes().remove(character);\n    }\n}</code>\n        </deckgo-highlight-code>\n<hr>\n<h2>📕 참고</h2>\n<ul>\n<li><a href=\"https://gyoogle.dev/blog/computer-science/data-structure/Trie.html\">Tech Interview for developer</a></li>\n<li><a href=\"https://hongjw1938.tistory.com/24\">자료구조-트라이(Trie)</a></li>\n<li><a href=\"https://ko.wikipedia.org/wiki/%ED%8A%B8%EB%9D%BC%EC%9D%B4_(%EC%BB%B4%ED%93%A8%ED%8C%85)#%EC%97%AD%EC%82%AC%EC%99%80_%EC%96%B4%EC%9B%90\">트라이</a></li>\n<li><a href=\"https://the-dev.tistory.com/3\">[자료구조] Trie(트라이)-2 : 자바로 구현하기</a></li>\n</ul>","frontmatter":{"title":"📂 Trie(트라이)","date":"May 25, 2022","update":"May 25, 2022","tags":["개발상식","Java","Trie"],"series":"📂 Computer Science"},"fields":{"slug":"/[CS]Trie/","readingTime":{"minutes":14.955}}},"seriesList":{"edges":[{"node":{"id":"3fe44622-13ba-589a-bbe8-01581ea7eb50","fields":{"slug":"/[CS]배열/"},"frontmatter":{"title":"📂 배열 (Array)"}}},{"node":{"id":"5b487c3d-e474-5a07-a26c-fc8c7d7cab22","fields":{"slug":"/[CS]연결리스트/"},"frontmatter":{"title":"📂 연결 리스트 (Linked List)"}}},{"node":{"id":"57149a6b-c730-5ce4-a3c5-9cea44979c8c","fields":{"slug":"/[CS]Array&ArrayList&LinkedList/"},"frontmatter":{"title":"📂 Array vs. ArrayList vs. LinkedList"}}},{"node":{"id":"28dac540-50bf-57df-afd9-9561888e8889","fields":{"slug":"/[CS]Stack&Queue/"},"frontmatter":{"title":"📂 Stack & Queue"}}},{"node":{"id":"4c2e96a9-4c71-57e3-b8e4-220b2cdf3002","fields":{"slug":"/[CS]Heap/"},"frontmatter":{"title":"📂 Heap"}}},{"node":{"id":"44f6bf8c-3235-5ff7-9d5f-f7c816218acb","fields":{"slug":"/[CS]Trie/"},"frontmatter":{"title":"📂 Trie(트라이)"}}},{"node":{"id":"81b508c5-2689-54e4-b36f-2e8bd07e2297","fields":{"slug":"/[CS]Tree/"},"frontmatter":{"title":"📂 Tree(트리)"}}},{"node":{"id":"2efb6036-05bf-594e-b9b5-03e399be6f78","fields":{"slug":"/[CS]이진탐색트리/"},"frontmatter":{"title":"📂 이진탐색트리(Binary Search Tree)"}}},{"node":{"id":"d1ac08af-f215-5176-9cd8-df1760f4ff7e","fields":{"slug":"/[CS]BTree&B+Tree/"},"frontmatter":{"title":"📂 B Tree & B+ Tree"}}}]},"previous":{"fields":{"slug":"/[Programmers]17683/"},"frontmatter":{"title":"👩‍💻 17683. 방금그곡"}},"next":{"fields":{"slug":"/[Programmers]17684/"},"frontmatter":{"title":"👩‍💻 17684. 압축"}}},"pageContext":{"id":"44f6bf8c-3235-5ff7-9d5f-f7c816218acb","series":"📂 Computer Science","previousPostId":"a3b26ae5-bd12-5412-b428-73dcdf98a075","nextPostId":"455b88fc-837a-51fe-8cfe-89ebf8a31d5e"}},"staticQueryHashes":[]}